import { Cascader, Checkbox, DatePicker, Form, Input, App, ModalProps, Result, Switch } from 'antd';
import dayjs from 'dayjs';
import { memo, useCallback, useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';

import orchestrationService from '@/api/services/orchestrationService';
import shareLinkSvc from '@/api/services/sharelink';
import { DatasetTypeEnum } from '@/common';
import { AppType, AppWorkbenchType } from '@/common/app/constants';
import { SvgIcon } from '@/components/icon';
import Modals from '@/components/modals/Modals';
import { useCopyToClipboard } from '@/hooks/event/use-copy-to-clipboard';
import useWindowWidth from '@/hooks/event/use-window-width';
import { useDatasetStore } from '@/store/datasetStore';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import { useShareLinkActions } from '@/store/sharelinkStore';
import { Sharelink, Permission } from '@/types/share-link';
import { findNodeById } from '@/utils/tree';

import { cvpermission, removeDuplicates } from '../utils/link-utils';

const { RangePicker } = DatePicker;
const { TextArea } = Input;
const { SHOW_CHILD } = Cascader;
type Props = {
  showCancelBtn?: boolean;
  showOkBtn?: boolean;
  initialValues?: Sharelink | undefined;
  appIdValue?: string;
  onCancel?: () => void;
} & ModalProps;

type FormValues = {
  name: string;
  description: string;
  status: boolean;
  time_range: [dayjs.Dayjs, dayjs.Dayjs];
  permissions: string[][];
};

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
  },
};

interface Option {
  key: string;
  value: string | number;
  label: React.ReactNode;
  name: string;
  children?: Option[];
}

const icons: Record<string, React.ReactNode> = {
  dataset: <SvgIcon icon="mdi--folder-zip" size={20} />,
  folder: <SvgIcon icon="ri--folder-2-fill" size={20} />,
};

const ShareLinkModal = ({ open, title, onCancel, initialValues, appIdValue }: Props) => {
  const [form] = Form.useForm<FormValues>();
  const { message } = App.useApp();
  const [isCreated, setIsCreated] = useState(false);
  const { allDatasets } = useDatasetStore();
  const [options, setOptions] = useState<Option[]>([]);
  const { getShareLinks } = useShareLinkActions();
  const [loading, setLoading] = useState(false);
  const [modalLoading, setModalLoading] = useState(false);
  const [checkTime, setCheckTime] = useState(false);

  const [shareUrl, setShareUrl] = useState('');
  const { isPc } = useWindowWidth();
  const { copyToClipboard } = useCopyToClipboard();

  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const appId = queryParams.get('appId') || appIdValue || '';
  const { shareId, appDetail, configurations } = useOrchestrationStore();

  const [isDatasetEnabled, setIsDatasetEnabled] = useState(false);

  const [initShareId, setInitShareId] = useState('');

  // 使用 useCallback 包裹，避免每次渲染都创建新函数，修复 useEffect 依赖警告
  const fetchAppDetail = useCallback(async () => {
    if (!appId) {
      return;
    }

    try {
      setModalLoading(true);
      const appDetailInfo = await orchestrationService.getAppDetailV2(
        appId,
        AppWorkbenchType.manage,
      );
      setInitShareId(appDetailInfo?.share_id || '');
      if (appDetailInfo?.appType === AppType.fusion) {
        setIsDatasetEnabled(false);
      } else if (appDetailInfo?.appType === AppType.workflow) {
        setIsDatasetEnabled(true);
      } else {
        // 智能体 根据 配置 判断
        const isDisableDataset =
          appDetailInfo?.configurations?.find((config) => config.name === 'disable_dataset')
            ?.default_value === '1' || false;
        setIsDatasetEnabled(!isDisableDataset);
      }
    } catch (error) {
      console.error(error);
    } finally {
      setModalLoading(false);
    }
  }, [appId]);

  useEffect(() => {
    if (open) {
      if (!appDetail?.appType) {
        fetchAppDetail();
      } else if (appDetail?.appType === AppType.fusion) {
        setIsDatasetEnabled(false);
      } else if (appDetail?.appType === AppType.workflow) {
        setIsDatasetEnabled(true);
      } else {
        // 智能体 根据 配置 判断
        const isDisableDataset =
          configurations?.find((config) => config.name === 'disable_dataset')?.default_value ===
            '1' || false;
        setIsDatasetEnabled(!isDisableDataset);
      }
    }
  }, [appDetail?.appType, configurations, fetchAppDetail, open]);

  // 递归生成options，使用useCallback避免每次渲染都创建新函数，修复useEffect依赖警告
  const generateOptions = useCallback((datasets: any[]): Option[] => {
    return datasets.map((dataset) => {
      const option: Option = {
        key: dataset.id || dataset._id,
        value: dataset.id || dataset._id,
        label: (
          <div className="inline-block" style={{ verticalAlign: 'middle' }}>
            <div className="flex items-center self-center">
              {icons[dataset.type]} <span className="ml-1">{dataset.name}</span>
            </div>
          </div>
        ),
        name: dataset.name,
        children: dataset.children ? generateOptions(dataset.children) : undefined,
      };
      return option;
    });
  }, []);

  const filter = (inputValue: string, path: Option[]) => {
    return path.some(
      (option) =>
        option?.name?.toString().includes(inputValue) ||
        (option &&
          option.children &&
          option?.children?.filter((c) => c.name.toString().includes(inputValue)).length > 0),
    );
  };

  const validForm = (value: FormValues) => {
    if (!value.name) {
      message.error('请输入分享链接名称');
      return false;
    }
    // if (!value.time_range) {
    //   message.error('请选择时间范围');
    //   return false;
    // }
    if (!value.permissions && isDatasetEnabled) {
      message.error('请选择需要分享的知识库');
      return false;
    }
    if (!value.description) {
      message.error('请输入说明');
      return false;
    }
    return true;
  };

  const onFinish = async (value: FormValues) => {
    console.log(value);

    try {
      if (!validForm(value)) {
        return;
      }
      const permission: Permission[] = [];
      if (value.permissions) {
        for (let index = 0; index < value.permissions.length; index++) {
          const elements = value.permissions[index];
          const id = elements[elements?.length - 1];
          const node = findNodeById(allDatasets, id);
          if (node) {
            permission.push({
              resource_id: node.id || node._id,
              resource_type: node.type,
              action: 'read',
              name: node.name,
            });
          }
        }
      }

      setLoading(true);
      let iat;
      let exp;
      if (checkTime) {
        iat = dayjs(value.time_range[0]).unix();
        exp = dayjs(value.time_range[1]).unix();
        if (iat > exp) {
          message.error('开始时间不能大于结束时间');
          return;
        }
      } else {
        iat = dayjs().unix();
        exp = dayjs().add(10, 'year').unix();
      }
      const req = {
        name: value.name,
        description: value.description,
        permissions: permission,
        iat,
        exp,
        status: value.status,
        app_id: appId,
      };
      if (initialValues && initialValues.id) {
        await shareLinkSvc.updateShareLink(initialValues.id, req);
        message.success('更新链接信息成功！');
        handleCancel();
      } else {
        const link = await shareLinkSvc.createShareLink(req);
        message.success('创建分享链接成功！');
        const url = `${window.location.origin}/sharelink/${link.share_code}/${appId}/${
          shareId || initShareId
        }`;
        copyToClipboard(url);
        setShareUrl(url);
        setIsCreated(true);
      }
      appId && (await getShareLinks(appId));
      // onCancel && onCancel(undefined);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    setIsCreated(false);
    form.resetFields();
    onCancel && onCancel();
  };

  useEffect(() => {
    const result = allDatasets.filter((item) => item.type !== 'function');
    setOptions(generateOptions(result.filter((item) => item.type !== DatasetTypeEnum.api)));
  }, [allDatasets, generateOptions]);

  useEffect(() => {
    if (initialValues) {
      // 初始化数据
      const cascaderData = cvpermission(allDatasets, initialValues.permissions);
      const res = removeDuplicates(cascaderData, initialValues.permissions ?? []);
      const value: FormValues = {
        name: initialValues.name,
        description: initialValues.description,
        status: initialValues.status,
        time_range: [dayjs(initialValues.iat * 1000), dayjs(initialValues.exp * 1000)],
        permissions: res,
      };
      form.setFieldsValue(value);
    } else {
      form.resetFields();
    }
  }, [allDatasets, form, initialValues]);

  return (
    <Modals
      destroyOnHidden={modalLoading}
      width={isPc ? '40%' : '100%'}
      className="share-link-modal"
      onCancel={() => {
        handleCancel();
        onCancel && onCancel();
      }}
      closable
      maskClosable={false}
      title={title}
      open={open}
      // footer={null}
      okText={isCreated ? '复制 & 关闭' : '确定'}
      onOk={isCreated ? handleCancel : form.submit}
      loading={modalLoading}
      confirmLoading={loading}
    >
      {!isCreated && (
        <Form
          form={form}
          name="basic"
          {...formItemLayout}
          initialValues={{ status: true }}
          autoComplete="on"
          onFinish={onFinish}
        >
          <Form.Item label="名称" name="name" wrapperCol={{ span: 16 }}>
            <Input
              allowClear
              bordered={false}
              className="share-link-input"
              placeholder="分享链接名称"
            />
          </Form.Item>

          <Form.Item label="说明" name="description" wrapperCol={{ span: 16 }}>
            <TextArea className="share-link-input" bordered={false} placeholder="链接说明" />
          </Form.Item>

          <Form.Item label="启用" name="status">
            <Switch />
          </Form.Item>

          <Form.Item label="设置有效期">
            <Checkbox
              value={checkTime}
              onChange={() => {
                setCheckTime(!checkTime);
              }}
            />
            {/* <Radio
              value={checkTime}
              onChange={() => {
                setCheckTime(!checkTime);
              }}
            ></Radio> */}
          </Form.Item>

          {checkTime && (
            <Form.Item name="time_range" label="时间范围">
              <RangePicker
                bordered={false}
                className="share-link-ant-picker"
                showTime
                format="YYYY-MM-DD HH:mm:ss"
              />
            </Form.Item>
          )}

          {isDatasetEnabled && (
            <Form.Item name="permissions" label="访客知识库">
              <Cascader
                className="share-link-cascader"
                style={{ width: '100%' }}
                options={options}
                placeholder="需要分享的知识库"
                multiple
                key="key"
                maxTagCount="responsive"
                showCheckedStrategy={SHOW_CHILD}
                // displayRender={displayRender}
                showSearch={{ filter }}
                popupClassName="share-link-modal-dropdown"
              />
            </Form.Item>
          )}
        </Form>
      )}
      {isCreated && <Result status="success" title="创建分享链接成功" subTitle={shareUrl} />}
    </Modals>
  );
};

export default memo(ShareLinkModal);
